package com.chase.framerwork.excel;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 解析Excel工具类,通过反射,实现通用
 * 
 * @author chase
 */
public class ExcelUtils
{

	/**
	 * 读取Excel方法名
	 */
	private static final String READ_EXCEL_METHOD = "readExcel";

	/**
	 * 写入Excel方法名
	 */
	private static final String WRITE_EXCEL_METHOD = "writeExcel";

	/**
	 * 读取Excel
	 * 
	 * @param request
	 *            request对象
	 * @param clazz
	 *            解析Excel的具体子类实现Class,该Class最大限定为AbsParseExcel.
	 * @param excel
	 *            需要读取的Excel对象
	 * @param params
	 *            其他参数
	 * @return List List中的每个对象都是Sheet页中的一行数据.
	 * @throws Exception
	 */
	public static List<?> readExcel(HttpServletRequest request, Class<? extends AbstractParseExcel<?>> clazz,
	        Excel excel, Object... params) throws Exception
	{

		Object object = clazz.newInstance();

		List<?> datalist = (List<?>) clazz.getDeclaredMethod(READ_EXCEL_METHOD,
		        new Class[] { HttpServletRequest.class, Excel.class, Object[].class }).invoke(object, request, excel,
		        params);

		return datalist;
	}

	/**
	 * 写入Excel
	 * 
	 * @param response
	 *            response对象
	 * @param clazz
	 *            解析Excel的具体子类实现Class,该Class最大限定为AbsParseExcel.
	 * @param excel
	 *            需要写入的Excel对象
	 * @param params
	 *            其他参数
	 * @throws Exception
	 */
	public static void writeExcel(HttpServletResponse response, Class<? extends AbstractParseExcel<?>> clazz,
	        Excel excel, List<?> resultList, String[] titles, Object... params) throws Exception
	{
		Object object = clazz.newInstance();

		AbstractParseExcel<?> parseExcel = (AbstractParseExcel<?>) object;

		parseExcel.setHeader(excel, titles);

		clazz.getDeclaredMethod(WRITE_EXCEL_METHOD,
		        new Class[] { HttpServletResponse.class, Excel.class, List.class, Object[].class }).invoke(object,
		        response, excel, resultList, params);

		parseExcel.setFooter(excel);

		parseExcel.responseExcel(response, excel);
	}

}
